import * as api from "@/api";

export default {
    namespaced: true,
    state: {
        boards: null,
        inite: false
    },
    getters: {
        getBoard: ({boards}) => id => Array.isArray(boards) ? boards.find(board => board.id == id) : null
    },
    mutations: {
        updateBoards: (state, data) => {
            state.boards = data;
            state.inited = true
        },
        addBoard: (state, data) => {
            if (state.boards == null) {
                state.boards = []
            }
            state.boards = [...state.boards, data]
        },
        delboard: (state, data) => {
            let temp = state.boards.find(board => board.id == data)
            let temps = []
            state.boards.map(item => {
                if (item != temp) {
                    temps.push(item)
                }
            })
            state.boards = temps
        },
        removeboard: (state) => {
            state.boards = null
            state.inite = false
        }

    },
    actions: {
        getBoards: async ({commit}) => {
            try {
                let rs = await api.getBoards();
                commit('updateBoards', rs.data)
                return rs
            } catch (e) {
                throw e;
            }
        },
        getBoard: async ({commit}, id) => {
            try {
                let rs = await api.getBoard(id);

                commit('addBoard', rs.data)
                return rs
            } catch (e) {
                throw e;
            }
        },
        postBoard: async ({commit}, data) => {
            try {
                let rs = await api.postBoard(data);
                commit('addBoard', rs.data)
                return rs
            } catch (e) {
                throw e
            }
        },
        deleteBoard: async ({commit}, data) => {
            try {
                let rs = await api.delBoard(data);
                commit('delboard', data)
                return rs
            } catch (e) {
                throw e
            }
        },
        removeboard: async ({commit}) => {
            commit('removeboard');
        }
    }

}
